<?php

/*
 * Fresns Control Panel (Standalone)
 * Copyright (C) 2021-Present 刘鑫
 * Released under the MIT License.
 */

namespace App\Plugins\FcpApi\TweetAdmin;

use App\Base\Controllers\BaseController;
use App\Http\Center\Common\ErrorCodeService;
use App\Http\Center\Common\ValidateService;
use App\Http\FresnsDb\FresnsUsers\FresnsUsers;
use App\Http\FresnsDb\FresnsUsers\FresnsUsersConfig;
use App\Plugins\FcpApi\Base\TweetBaseController;
use App\Plugins\FcpApi\TweetSessionKeys\TweetSessionKeys;
use App\Plugins\FcpApi\TweetUsers\TweetUsers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class LoginController extends TweetBaseController
{
    use AuthenticatesUsers;

    public function __construct()
    {
        $this->checkRequest();
    }

    /**
     * 管理员登录.
     *
     * @param  Request  $request
     */
    public function adminLogin(Request $request)
    {
        $rule = [
            'name' => 'required',
            'password' => 'required',
        ];
        ValidateService::validateRule($request, $rule);

        $account = $request->input('name');
        $password = $request->input('password');

        //通过session_keys > type = 2 session_keys > plugin_unikey = Tweet 去查询是否存在
        $session = TweetSessionKeys::where('type', 2)->where('plugin_unikey', 'FcpApi')->where('app_id', $account)->where('app_secret', $password)->where('is_enable', 1)->first();

        if (empty($session)) {
            $this->error(ErrorCodeService::HEADER_PLATFORM_ERROR);
        }
        // 定义用户身份 默认id为1
        $userId = 1;
        $user = TweetUsers::where('is_enable', 1)->where('id', $userId)->first();

        if (empty($user)) {
            $this->error(ErrorCodeService::USER_CHECK_ERROR);
        }

        $result = Auth::loginUsingId(1);

        if (! $result) {
            $this->error(ErrorCodeService::USER_CHECK_ERROR);
        }

        $user = Auth::user();

        //默认跳转地址
        $jumpLogin = '/dashboardTweet/dashboard-index';
        $user['jump_url'] = $jumpLogin;
        $user['login_name'] = 'admin';
        $user['app_id'] = $session['app_id'];
        $user['app_secret'] = $session['app_secret'];
        $user['platform'] = $session['platform_id'];

        $this->success($user);
    }

    /**
     * 管理员登出.
     *
     * @param  Request  $request
     */
    public function adminLogout(Request $request)
    {
        //  dd(Auth::guard('api')->check());
        // 检查是否登录
        if (Auth::guard('api')->check()) {
            //判断是否有登录日志表,并插入数据
            Auth::logout();
        }

        $this->success();
    }

    public function currentUser(Request $request)
    {
        $user = Auth::user();

        $apiToken = DB::table('session_tokens')->where('user_id', $user->id)->value('token');
        $currentUser = [];
        $currentUser['authority'] = ['admin'];
        $currentUser['token'] = $apiToken;
        $currentUser['access_token'] = $apiToken;
        $currentUser['token_type'] = 'Bearer';
        $currentUser['type'] = 'admin';
        $currentUser['redirect_url'] = '';
        $currentUser['avatar'] = $user['file_url'] ?? 'https://cdn.fresns.cn/images/default_avatar.png';

        $currentUser['login_name'] = 'admin';
        $currentUser['nickname'] = 'Fresns';
        $currentUser['userid'] = $user['id'];
        $currentUser['email'] = $user['email'];
        $currentUser['remark'] = $user['remark'];
        $currentUser['id'] = $user['id'];

        $testData = '{"code":0,"msg":"ok","data":{"name":"admin","loginName":"","modify":"0","postCount":"0","viewCount":"0","coin":"0","signature":"\u6d77\u7eb3\u767e\u5ddd\uff0c\u6709\u5bb9\u4e43\u5927","title":"\u4ea4\u4e92\u4e13\u5bb6","group":"haod","tags":[{"key":"0","label":"\u5f88\u6709\u60f3\u6cd5\u7684"},{"key":"1","label":"\u4e13\u6ce8\u8bbe\u8ba1"},{"key":"2","label":"\u8fa3~"},{"key":"3","label":"\u5927\u957f\u817f"},{"key":"4","label":"\u5ddd\u59b9\u5b50"},{"key":"5","label":"\u6d77\u7eb3\u767e\u5ddd"}],"notifyCount":12,"country":"China","geographic":{"province":{"label":"\u6d59\u6c5f\u7701","key":"330000"},"city":{"label":"\u676d\u5dde\u5e02","key":"330100"}},"address":"\u897f\u6e56\u533a\u5de5\u4e13\u8def 77 \u53f7","commentCount":"0","phone":"185****3333"}}';
        $testDataArr = json_decode($testData, true);

        $data = array_merge($currentUser, $testDataArr['data']);
//        dd($data);

        $this->success($data);
    }
}
